import React, { Component } from "react";

export default class Page extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // total: 100, //数据总数
      // showPage: 7, //连续的页码个数
      // shownum: 9, //每页显示十条数据
      pageIndex: 1, //默认显示第一页  选择的是第几页
      list: [], //需要显示的页码
    };
  }
  prev = () => {
    this.change(this.state.pageIndex - 1);
  };
  next = () => {
    this.change(this.state.pageIndex + 1);
  };
  change = (index) => {
      this.setState({
        pageIndex:index
      })
  };
  static getDerivedStateFromProps(props, state){

    if(state.total!==props.total){//说明了数据总数发生了变化
        state.pageIndex =1;
    }
    state.total = props.total; //第一次进来 state和props中的值是一样的


    return  {}

  }

  render() {
    //三个 list ,pageindex,maxPage
    //页面加载完成
    //我怎么知道props的total发生了改变

    let maxPage = Math.ceil(this.props.total / this.props.shownum);
    //向上取整  12   2
    let middleNum = Math.ceil(this.props.showPage / 2); //5/2 =2.5  3
    let start = 1; //第一页开始
    let end = maxPage > this.props.showPage ? this.props.showPage : maxPage;
    //结束的页码
    //默认的开头
    //到了中间
    if (this.state.pageIndex > middleNum) {
      //大于3
      start = this.state.pageIndex - middleNum + 1;
      end =this.state.pageIndex + middleNum - 1;
    }
    //到了最后
    if (this.state.pageIndex > maxPage - middleNum) {
      //12-4 8
      start = maxPage - this.props.showPage + 1;
      end = maxPage;
    }
    start = start > 1 ? start : 1;
    //开头的检查
    let list = []; //清空
    for (var i = start; i <= end; i++) {
      list.push(i);
    }
    this.props.onChange(this.state.pageIndex);
    
    return (
      <div className="page">
        {this.state.pageIndex === 1 ? (
          <div className="page-prev disabled">上一页</div>
        ) : (
          <div
            className="page-prev"
            onClick={() => {
              this.prev();
            }}
          >
            上一页
          </div>
        )}

        <div className="page-content">
          {list.map((item, index) => {
            return (
              <div
                className={
                  item === this.state.pageIndex
                    ? "page-item active"
                    : "page-item"
                }
                key={index}
                onClick={() => {
                  this.change(item);
                }}
              >
                {item}
              </div>
            );
          })}
        </div>
        {this.state.pageIndex === maxPage ? (
          ""
        ) : (
          <div
            className="page-next"
            onClick={() => {
              this.next();
            }}
          >
            下一页
          </div>
        )}
      </div>
    );
  }
}
